rm(list=ls())

load("TSCS_data_reduced.RData")

# Figure 1

panel %>%
  as.data.frame() %>%
  mutate(percentile = ntile(downturn, 20),
         upper_cases = if_else(percentile == 20, 'Upper','Lower')) %>%
  filter(upper_cases == 'Upper') %>%
  mutate(country_name = droplevels(country_name)) ->
  country_upper

country_upper_list <- levels(country_upper$country_name)

panel %>% as.data.frame() %>%
  mutate(liberal_democracy = liberal_democracy / 100,
         antipluralism_gov_seat_share = scales::rescale(antipluralism_gov_seat_share, to = c(0,1)),
         citizen_support = scales::rescale(citizen_support, to = c(0,1))) %>%
  filter(country_name%in%country_upper_list) %>%  
  select(year,country_name,liberal_democracy,antipluralism_gov_seat_share,citizen_support) %>% 
  gather(key = measure, value = value, liberal_democracy,antipluralism_gov_seat_share,citizen_support) ->
  figure_data

figure_data %>%
  convert(num(year)) %>%
  ggplot(aes(x=year, y = value, group = measure, colour = measure, linetype=measure)) +
  geom_line(linewidth=0.5) + 
  facet_wrap(~country_name,ncol = 4, scales="fixed") + 
  ylab("") + 
  xlab("Year") +
  theme(legend.title = element_blank()) +
  scale_colour_discrete(breaks=c("antipluralism_gov_seat_share", "citizen_support","liberal_democracy"),
                        labels=c("Anti-pluralist Government", "Citizen Support","Liberal Democracy")) + 
  scale_linetype_discrete(breaks=c("antipluralism_gov_seat_share", "citizen_support","liberal_democracy"),
                          labels=c("Anti-pluralist Government", "Citizen Support","Liberal Democracy")) + 
  theme(legend.position="bottom") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) ->
  fig1

fig1

ggsave(fig1, filename = "fig_1.pdf", device = cairo_pdf, 
       width = 9.5, height = 10, units = "in")